from ..io import OMSSAResults



def consistencyCheck(raw, ShortFilter):
	Acclist = {}
	filtered = xlh.OMSSAResults()


	# we are trying to parse only matches with a single x-mod... possibly not on the last aa
	for m in raw.items():
		
		xcount = 0	# counter for x-modifications in results
		
		# defining NPeptide and CPeptide now is only useful to understand
		# if the x-mod is on the last aminoacid of single peptides
		
		NPeptide = map(lambda x: x.split(':'), m.proteinDescription().split())[0][0]
		if m.peptide().find(NPeptide) == 0:
			CPeptide = map(lambda x: x.split(':'), m.proteinDescription().split())[1][0]
		else:
			CPeptide = map(lambda x: x.split(':'), m.proteinDescription().split())[0][0]
			NPeptide = map(lambda x: x.split(':'), m.proteinDescription().split())[1][0]
	
		if len(NPeptide) < ShortFilter or len(CPeptide) <= ShortFilter:
			continue
	
		if NPeptide + CPeptide == m.peptide() or CPeptide + NPeptide == m.peptide():
			# x-peptide sequence should be a combination of single peptides
			# this is the first, slowest test...
			for (pos, mod) in m.modifications().items():
				if mod in XlinkerList:
					# first of all check that modification is not on
					# C-terminal of one of single peptides...
					# this check should be made atomic because I'm not sure
					# every xlinker needs this
					
					# pos, the position, is relative to x-peptide, we should map it
					# on single peptides.
					if pos == len(NPeptide) or pos == len(m.peptide()):
						# len(NPeptide) corresponds to the length of left peptide
						# pos is given starting from 1, so that if the modification is on 
						# the C-terminal of Left peptide, pos == len(NPeptide)
						# for the same reason, pos == len(m.peptide()) means that modification
						# is on C-term of CPeptide...
						# in this case we set xcount to a value greater than 2 and get ot
						# this loop
						xcount = 2
						break # breaks this loop of modifications...
					
					# after all count how many xlinkers we have
					# they should not be more than one per peptide
					xcount += 1
			if xcount == 1:
				# we should find just one x-mod for each peptide
				filtered.addMatch(m)
				
				# get accession for proteins... we can do this later and possibly in a more elegant
				# form, but this saves a lot of time !!!
				for p in map(lambda x: x.split(':'), m.proteinDescription().split())[0][1].split(','):
					Acclist[p] = 1
				for p in  map(lambda x: x.split(':'), m.proteinDescription().split())[1][1].split(','):
					Acclist[p] = 1
		
	return (filtered, Acclist)